from dotenv import load_dotenv
from langchain import hub
from langchain.agents import AgentExecutor, create_tool_calling_agent, create_openai_tools_agent
from langchain.chat_models import init_chat_model
from langchain_core.tools import tool
import nest_asyncio
from playwright.sync_api import Browser

from src.Basic.tools.browser import get_browser

load_dotenv(override=True)

browser_instance:Browser|None = None
@tool
def summary_website(url):
    """
    使用浏览器访问网站并返回总结
    :param url: 网站的URL
    :return: 网站内容的总结
    """
    global browser_instance

    #定义模型
    model = init_chat_model(model="deepseek-chat", model_provider="deepseek")
    # 定义 天气查询 工具函数
    if browser_instance is None:
        tools,sync_browser = get_browser(None)
        browser_instance = sync_browser
    else:
        tools, sync_browser = get_browser(browser_instance)

    prompt = hub.pull("hwchase17/openai-tools-agent")
    agent = create_tool_calling_agent(llm=model,tools=tools,prompt=prompt)
    agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
    try:
        #并行
        response = agent_executor.invoke({"input": f"访问这个网站 {url} 并帮我详细总结一下这个网站的内容，包括主要功能、特点和使用方法"})
        return response['output'],
    except Exception as e:
        return f"访问网站时出错: {str(e)}"